package cn.javaxxw.springboot;

import lombok.experimental.UtilityClass;

import java.util.Random;

@UtilityClass
public class RandomUtils {

    /**
     * 带权重的随机决策——基于线性扫描
     * 注意：
     * 1. 时间复杂度O(n)，n = prizePool.length
     * 2. 将权重大的数据靠前，可以减少列表遍历的次数
     *
     * @param prizePool  - 需要决策的数据
     * @param weightPool - 数据所占的权重（决定数据被选中的概率）
     * @param <E>        - 数据类型
     * @return -
     */
    public static <E> E randomDecisionWithWeight(E[] prizePool, int[] weightPool) {
        if (prizePool.length == 0 || prizePool.length != weightPool.length) {
            throw new IllegalArgumentException();
        }


        // 计算总权重，确定随机数生成范围
        int weightSum = 0;
        for (int weight : weightPool) {
            if (weight < 0) {
                throw new IllegalArgumentException("权重不允许是负数！");
            }
            weightSum += weight;
        }

        // 抽取数据
        int randomPrizePoint = new Random().nextInt(weightSum);
        E randomPrize = null;
        for (int i = 0; i < weightPool.length; i++) {
            if (randomPrizePoint < weightPool[i]) {
                randomPrize = prizePool[i];
                break;
            } else {
                randomPrizePoint -= weightPool[i];
            }
        }

        return randomPrize;
    }

    /**
     * 功能：随机产生18-21的整数
     *
     * @return
     */
    public int getAge() {
        return new Random().nextInt(4) + 18;
    }


    /**
     * 生成随机数
     * @return
     */
    public String getRandomNum(){
        Random rand = new Random();
        StringBuilder random = new StringBuilder();
        for(int a = 0; a < 6; a++){
            random.append(rand.nextInt(10));//生成6位数字
        }
        return random.toString();
    }


}
